package com.ly.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Shop3 {
    private static int flag = 1;

    private Lock lock = new ReentrantLock();

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void f1() {
        lock.lock();
        try{
            while(flag != 1 ) {
                condition1.await();
            }
            flag = 2;
            System.out.println(Thread.currentThread().getName());
            condition2.signal();
        }catch(Exception e){

        }finally {
            lock.unlock();
        }

    }

    public void f2() {
        lock.lock();
        try{
            while(flag != 2 ) {
                condition2.await();
            }
            flag = 3;
            System.out.println(Thread.currentThread().getName());
            condition3.signal();
        }catch(Exception e){

        }finally {
            lock.unlock();
        }

    }

    public void f3() {
        lock.lock();
        try{
            while(flag != 3 ) {
                condition3.await();
            }
            flag = 1;
            System.out.println(Thread.currentThread().getName());
            condition1.signal();
        }catch(Exception e){

        }finally {
            lock.unlock();
        }

    }
}

public class ThreadCondition2 {
    public static void main(String[] args) {
        Shop3 shop3 = new Shop3();
        for(int i=0;i<10;i++) {
            new Thread(() -> { shop3.f1();},"a").start();
            new Thread(() -> { shop3.f2();},"b").start();
            new Thread(() -> { shop3.f3();},"c").start();
        }

    }
}
